const fileService = require('../service/file.service');
const userService = require('../service/user.service');
const {APP_HOST, APP_PORT} = require('../app/config');

class FileController {

  // 保存头像信息
  async saveAvatarInfo(ctx, next) {
    // 1.获取图像信息
    const {filename, mimetype, size} = ctx.req.file;
    const {id} = ctx.user;
    const avatarUrl = `${APP_HOST}:${APP_PORT}/users/${id}/avatar`;
    // 2.将图像数据保存到数据库
    await fileService.saveAvatarInfo(filename, mimetype, size, id);
    await userService.updateAvatarByUserId(avatarUrl, id);
    // 3.返回结果
    ctx.body = {
      code: 200,
      message: "上传头像成功"
    };
  }

  // 保存cover图片
  async saveCoverInfo(ctx, next) {
    // 1.获取cover信息
    const {filename, mimetype, size} = ctx.req.file;
    const {id} = ctx.user;
    const coverUrl = `${APP_HOST}:${APP_PORT}/users/${id}/cover`;
    // 2.将cover数据保存到数据库
    await fileService.saveCoverInfo(filename, mimetype, size, id);
    await userService.updateCoverByUserId(coverUrl, id);
    // 3.返回结果
    ctx.body = {
      code: 200,
      message: "上传cover成功"
    };
  }

  // 保存动态配图
  async savePictureInfo(ctx, next) {
    // 1.获取图像信息
    const files = ctx.req.files;
    const {id} = ctx.user;
    const {momentId} = ctx.query;
    // 2.保存图片
    for (let file of files) {
      const {filename, mimetype, size} = file;
      await fileService.saveFile(filename, mimetype, size, id, momentId);
    }
    ctx.body = {
      code: 200,
      message: "动态配图上传完成"
    }
  }

  // 保存所有壁纸
  async saveWallInfo(ctx, next) {
    // 1.获取图像信息
    const files = ctx.req.files;
    const {id} = ctx.user;
    // 2.保存图片
    for (let file of files) {
      const {filename, mimetype, size} = file;
      await fileService.saveWallInfo(filename, mimetype, size, id);
    }
    ctx.body = {
      code: 200,
      message: "上传壁纸成功"
    }
  }

  // 保存文章配图
  async saveArticlePicInfo(ctx, next) {
    // 1.获取文章配图信息
    const {filename, mimetype, size} = ctx.req.file;
    const {id} = ctx.user;
    // 2.将数据保存到数据库
    const result = await fileService.saveArticlePicInfo(filename, mimetype, size, id);
    // 3.返回结果
    if (result.insertId) {
      result.url = `${APP_HOST}:${APP_PORT}/article/pic/${filename}`;
    }
    ctx.body = result;
  }

}

module.exports = new FileController();
